/*
 * @Author: AskMeWhy
 * @Date:   2019-09-10 17:55:01
 * @Last Modified by: AskMeWhy
 * @Last Modified time: 2021-06-22 11:51:21
 */
import Vue from "vue";
import * as rules from "vee-validate/dist/rules";
import { ValidationObserver, ValidationProvider, extend } from "vee-validate";
import { isObject, isEmptyObject } from "./tool.kit";
// import { required } from "vee-validate/dist/rules"

Vue.component("ValidationObserver", ValidationObserver);
Vue.component("ValidationProvider", ValidationProvider);
Object.keys(rules).forEach((rule: any) => {
    extend(rule, {
        ...rules[rule]
    });
});
extend("required", {
    message: "该字段为必填项！",
    validate(value: any) {
        let _valid = true;
        if (Array.isArray(value)) {
            _valid = value.length !== 0;
        } else if (isObject(value)) {
            _valid = !isEmptyObject(value);
        } else {
            _valid = ["", null, undefined].indexOf(value) === -1;
        }
        return {
            required: true,
            valid: _valid
        };
    },
    computesRequired: true
});

const decimalValidate = (value: any, { decimals, separator }: any) => {
    value = String(value);
    const valueDecimals = value.split(separator)[1] ? value.split(separator)[1].length : -1;
    // if is 0.
    if (Number(decimals) === 0) {
        return /^-?\d*$/.test(value);
    }

    const regexPart = decimals === "*" ? "+" : `{1,${decimals}}`;
    const regex = new RegExp(
        `^[-+]?\\d*(\\${separator}\\d${regexPart})?([eE]{1}[-]?\\d+)?$`
    );
    if (!regex.test(value)) {
        if (valueDecimals > Number(decimals)) {
            return `至多保留${decimals}位小数`;
        }
        return false;
    }
    if (valueDecimals !== -1 && valueDecimals < Number(decimals)) {
        return `请输入${decimals}位小数`;
    }
    const parsedValue = parseFloat(value);

    // eslint-disable-next-line
    return parsedValue === parsedValue;
};
extend("decimal", {
    message: "请输入数字",
    validate(value: any, args: any) {
        const decimals = args[0] || "*";
        const separator = args[1] || ".";
        // eslint-disable-next-line no-void
        if (value === null || value === void 0 || value === "") {
            return false;
        }

        if (Array.isArray(value)) {
            return value.every(val =>
                decimalValidate(val, { decimals, separator })
            );
        }

        return decimalValidate(value, { decimals, separator });
    }
});


export const checkPassword = (value: any) => {
    const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/;
    return reg.test(value);
};

extend("customPassword", {
    message: "请设置6~12位数字字母组合新密码！",
    validate(value: any) {
        return {
            required: true,
            valid: checkPassword(value)
        };
    },
    computesRequired: true
});
